﻿using Exam.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Exam.DAL
{
    public class ShoppingDAL
    {
        ShoppingDBEntities entities;
        public ShoppingDAL()
        {
            entities = new ShoppingDBEntities();
        }


        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="admin"></param>
        /// <returns></returns>
        public bool Login(string user,string pwd)
        {
            if (entities.Admins.FirstOrDefault(x=>x.Username==user&&x.Password==pwd)!=null)
            {
                return true;
            }
            return false;
        }


        /// <summary>
        /// 添加商品
        /// </summary>
        /// <param name="product"></param>
        /// <returns></returns>
        public bool AddProduct(Product product)
        {
            entities.Products.Add(product);
            return entities.SaveChanges() > 0;
        }


        /// <summary>
        /// 删除商品
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public bool RemoveProduct(int? id)
        {
            var find = entities.Products.Find(id);
            entities.Products.Remove(find);
            return entities.SaveChanges() > 0;
        }


        /// <summary>
        /// 查询所有商品
        /// </summary>
        /// <returns></returns>
        public List<Product> GetProducts()
        {
            return entities.Products.ToList();
        }


        /// <summary>
        /// 根据id查找产品
        /// </summary>
        /// <param name="id">产品id</param>
        /// <returns></returns>
        public Product GetProducts(int? id)
        {
            return entities.Products.FirstOrDefault(x => x.PId == id);
        }


        /// <summary>
        /// 分页
        /// </summary>
        /// <param name="pageNum">页号</param>
        /// <param name="pageSize">每页的数量</param>
        /// <returns></returns>
        public List<Product> GetProducts(int pageNum, int pageSize)
        {
            return entities.Products.OrderBy(x => x.PId).Skip((pageNum - 1) * pageSize).Take(pageSize).ToList();
        }



        /// <summary>
        /// 更改产品
        /// </summary>
        /// <param name="product"></param>
        /// <returns></returns>
        public bool ModifyProduct(Product product)
        {
            entities.Entry(product).State = System.Data.Entity.EntityState.Modified;
            return entities.SaveChanges() > 0;
        }
    }
}